package com.aos.erp.manager.service.applyschool.impl;


import com.aos.erp.common.bean.IPageBean;
import com.aos.erp.common.bean.ResultEntity;
import com.aos.erp.common.constant.GlobalConstant;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.common.redis.RedisService;
import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.manager.enums.SmsType;
import com.aos.erp.manager.mapper.applyschool.ApplySchoolDeviceMapper;
import com.aos.erp.manager.mapper.applyschool.ApplySchoolMapper;
import com.aos.erp.manager.mapper.applyschool.ApplySchoolPicMapper;
import com.aos.erp.manager.model.applyschool.entity.ApplySchool;
import com.aos.erp.manager.model.applyschool.entity.ApplySchoolDevice;
import com.aos.erp.manager.model.applyschool.entity.ApplySchoolPic;
import com.aos.erp.manager.model.applyschool.ro.*;
import com.aos.erp.manager.model.applyschool.vo.*;
import com.aos.erp.manager.remote.DivisionService;
import com.aos.erp.manager.remote.MessageService;
import com.aos.erp.manager.remote.model.Division;
import com.aos.erp.manager.service.applyschool.ApplySchoolService;
import com.aos.erp.manager.service.sys.DepartmentService;
import com.aos.erp.manager.service.sys.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.aos.erp.manager.model.sys.vo.SchoolUserVo;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * AOS驾校管理 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2018-10-31
 */
@Service
public class ApplySchoolServiceImpl extends ServiceImpl<ApplySchoolMapper, ApplySchool> implements ApplySchoolService {

	private static int captchaExpires = 5 * 60; //超时时间5min

	@Resource
	private ApplySchoolMapper            applySchoolMapper;
	@Resource
	private DepartmentService            departmentService;
	@Resource
	private DivisionService              divisionService;
	@Resource
	private ApplySchoolDeviceMapper      applySchoolDeviceMapper;
	@Resource
	private ApplySchoolPicMapper         applySchoolPicMapper;
	@Resource
	private GlobalConstant               globalConstant;
	@Resource
	private UserService                  userService;
	@Resource
	private MessageService               messageService;
	@Autowired
	private RedisService                  redisService;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public IPageBean queryByPage(QueryApplySchoolRo queryGatherSchoolRo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", queryGatherSchoolRo.getName());
		if (queryGatherSchoolRo.getStatus() != null) {
			map.put("status", queryGatherSchoolRo.getStatusNum());
		}
		map.put("mobile", queryGatherSchoolRo.getMobile());
		map.put("provinceId", queryGatherSchoolRo.getProvinceId());
		map.put("cityId", queryGatherSchoolRo.getCityId());
		map.put("areaId", queryGatherSchoolRo.getAreaId());
		map.put("divisionId", queryGatherSchoolRo.getDivisionId());
		IPage<ApplyListVo> page = new Page<ApplyListVo>(queryGatherSchoolRo.getPageIndex() == null ? 1 : queryGatherSchoolRo.getPageIndex(), queryGatherSchoolRo.getPageSize() == null ? 10 : queryGatherSchoolRo.getPageSize());
		map.put("pageBean", page);
		List<ApplyListVo> list = applySchoolMapper.queryListShow(map);
		page.setRecords(list);
		return baseMapper.toBizPage(page);
	}

	/**
	 * 查看申请记录信息
	 *
	 * @param id 驾校ID
	 * @return
	 */
	@Override
	public ApplyInfoVo applyInfo(long id) throws BizException {
		ApplyInfoVo applySchool = applySchoolMapper.queryObject(id);
		if (applySchool == null) {
			throw new BizException("驾校信息错误");
		}
		//查询图片
		Map<String, Object> map = new HashMap<>();
		map.put("driversSchoolId",applySchool.getId());
		List<ApplySchoolPic> pics=applySchoolPicMapper.queryList(map);
		String schoolPics="";
		String licensePics="";
		if(pics.size()>0){
			for(ApplySchoolPic applySchoolPic:pics){
				if(applySchoolPic.getType()==1){
					schoolPics=schoolPics+applySchoolPic.getFileId()+",";
				}else {
					licensePics=licensePics+applySchoolPic.getFileId()+",";
				}
			}
		}
		if(schoolPics!=""){
			schoolPics=schoolPics.substring(0,schoolPics.length()-1);
		}
		if(licensePics!=""){
			licensePics=licensePics.substring(0,licensePics.length()-1);
		}
		applySchool.setSchoolPics(schoolPics);
		applySchool.setLicensePics(licensePics);
		if (applySchool.getType() < 3) {
			//如果为总校，直接返回
			return applySchool;
		} else {
			ApplySchool as = this.baseMapper.selectById(applySchool.getParentId());
			if (as == null) {
				throw new BizException("父级驾校信息错误");
			}
			if (as.getType() < 3) {
				//如果为总校，直接返回
				applySchool.setGatherId(as.getId());
				applySchool.setGatherName(as.getName());
			} else {
				ApplySchool as1 = this.baseMapper.selectById(as.getParentId());
				if (as1 == null) {
					throw new BizException("总校信息错误");
				}
				applySchool.setBranchId(as.getId());
				applySchool.setGatherId(as1.getId());
				applySchool.setGatherName(as1.getName());
			}
			return applySchool;
		}
	}

	@Override
	public void editApply(ReviewApplyRo reviewApply) throws Exception {
		ApplySchool applySchool = this.baseMapper.selectById(reviewApply.getId());
		if (applySchool == null) {
			throw new BizException("驾校信息错误");
		}
		if(applySchool.getStatus()==2){
			throw new BizException("驾校已审核通过！");
		}
		//TODO RoldId 未处理，待定
		//Integer status = Integer.parseInt(reviewApply.getStatusNum().toString());
		Integer status = reviewApply.getReviewResult();
		Date date = new Date();
		String depCode = "";
		Long depId;
		applySchool.setRemark(reviewApply.getRemark());
		applySchool.setUpdated(date);
		applySchool.setAuditdate(date);
		applySchool.setCreateUser(Long.parseLong(reviewApply.getCurrentUserId()));
		applySchool.setParentId(reviewApply.getParentId());
		if (status == 2) {
			//审核成功
			applySchool.setStatus(2);
			//获取depCode( 报名点类型 )
			if (applySchool.getType() == 4) {
				if(reviewApply.getParentId()==null){
					throw new BizException("父级驾校不能为空");
				}
				ApplySchool gs = this.baseMapper.selectById(reviewApply.getParentId());
				depCode = departmentService.getDepCodeBranch(gs.getDepCode(), "B");
				applySchool.setDepCode(depCode);
				this.baseMapper.updateById(applySchool);
				depId=departmentService.addBeanSchoolBranch(gs.getDepCode(), depCode, applySchool.getName(), "B",globalConstant.getAPP_CODE_AOS());
			} else {
				//获取depCode( 总校 )
				Division division = divisionService.Info(applySchool.getDivisionId());
				depCode = departmentService.getDepCodeSchool(division.getDepCode());
				applySchool.setDepCode(depCode);
				this.baseMapper.updateById(applySchool);
				depId=departmentService.addBeanSchool(division.getDepCode(), depCode, applySchool.getName(),globalConstant.getAPP_CODE_AOS());
			}
			//初始化驾校账号，组织
			SchoolUserVo schoolUserVo=new SchoolUserVo();
			schoolUserVo.setDepCode(depCode);
			schoolUserVo.setDepId(depId);
			schoolUserVo.setName(applySchool.getName());
			schoolUserVo.setUsername(applySchool.getMobile());
			schoolUserVo.setPassword(applySchool.getPassword());
			schoolUserVo.setOperatorId(Long.parseLong(reviewApply.getCurrentUserId()));
			userService.addBeanSchool(schoolUserVo,globalConstant.getAPP_CODE_SCHOOL());
		} else if (status == 3) {
			//审核失败
			applySchool.setStatus(3);
			this.baseMapper.updateById(applySchool);
		}

	}

	@Override
	public SchoolNameVo gatherNameByCode(String code) throws BizException {
		List<SchoolNameVo> list= applySchoolMapper.gatherNameByCode(code);
		if(list.size()>1){
			throw new BizException("总校信息错误");
		}
		if(list.size()<1){
			throw new BizException("未找到总校");
		}
		return list.get(0);
	}

	@Override
	public LoginResultRo queryResult(LoginUserRo loginUserRo) throws BizException {
		LoginResultRo loginResultRo = new LoginResultRo();
		Map<String, Object> map = new HashMap<>();
		map.put("phone", loginUserRo.getUsername());
		map.put("password", loginUserRo.getPassword());
		List<ApplySchool> list = applySchoolMapper.queryList(map);
		if (list.size() != 1) {
			throw new BizException("信息查询错误，请联系管理员");
		}
		ApplySchool ApplySchool = list.get(0);
		loginResultRo.setId(ApplySchool.getId());
		loginResultRo.setRemark(ApplySchool.getRemark());
		loginResultRo.setStatus(ApplySchool.getStatus());
		return loginResultRo;
	}

	/**
	 * 申请驾校
	 *
	 * @param applySchoolRo 申请驾校实体
	 * @return
	 */
	@Override
	public void applySchool(ApplySchoolRo applySchoolRo) throws BizException {
		//验证驾校
		if(applySchoolRo.getType()<3){
			Map<String, Object> map = new HashMap<>();
	//		map.put("valiMobile", applySchoolRo.getMobile());
	//		map.put("valiName", applySchoolRo.getName());
			map.put("valiCode", applySchoolRo.getCode());
			List<ApplySchool> ApplySchoolRo = applySchoolMapper.queryList(map);
			if (ApplySchoolRo.size() > 0) {
				throw new BizException("请检查手机号码，驾校名称，驾校代码是否唯一！");
			}
		}
		Date date = new Date();
		applySchoolRo.setCreated(date);
		applySchoolRo.setUpdated(date);
		applySchoolRo.setIsDel(0);
		applySchoolRo.setStatus(1);
		ApplySchool applySchool = new ApplySchool();
		BeanUtils.copyProperties(applySchoolRo, applySchool);
		if(applySchoolRo.getType()<3){
			applySchool.setParentId((long)0);
			if(applySchoolRo.getLicensenumber()==null||applySchoolRo.getLicensenumber()==""){
				throw new BizException("请填入营业执照注册号！");
			}
			if(applySchoolRo.getCode()==null||applySchoolRo.getCode()==""){
				throw new BizException("请填入总校代码！");
			}
		}else{
			applySchool.setCode("");
			applySchool.setLicensenumber("");
		}
		//applySchool.setCreateUser(applySchoolRo.getCurrentUserId());
		this.baseMapper.insert(applySchool);
		if (applySchoolRo.getDevicecode() != null || applySchoolRo.getUsbKey() != null) {
			//新增设备
			ApplySchoolDevice applySchoolDevice = new ApplySchoolDevice();
			applySchoolDevice.setCreated(date);
			applySchoolDevice.setUpdated(date);
			applySchoolDevice.setDevicecode(applySchoolRo.getDevicecode());
			applySchoolDevice.setUsbKey(applySchoolRo.getUsbKey());
			applySchoolDevice.setIsDel(0);
			applySchoolDevice.setDriversSchoolId(applySchool.getId());
			applySchoolDeviceMapper.insert(applySchoolDevice);
		}
		if (applySchoolRo.getSchoolPics() != null) {
			//新增驾校图片
			String[] schoolPic = applySchoolRo.getSchoolPics().split(",");
			if (schoolPic.length > 10) {
				throw new BizException("驾校图片最多上传10张！");
			}
			//新增营业执照图片
			ApplySchoolPic applySchoolPic = new ApplySchoolPic();
			applySchoolPic.setCreated(date);
			applySchoolPic.setUpdated(date);
			applySchoolPic.setIsDel(0);
			applySchoolPic.setDriversSchoolId(applySchool.getId());
			applySchoolPic.setType(2);
			for (int i = 0; i < schoolPic.length; i++) {
				if (schoolPic[i].trim() == ""||schoolPic[i].trim() == null) {
					continue;
				}
				applySchoolPic.setFileId(Long.parseLong(schoolPic[i]));
				applySchoolPicMapper.insert(applySchoolPic);
			}
		}
		if (applySchoolRo.getLicensenPics() != null) {
			String[] licensenPic = applySchoolRo.getLicensenPics().split(",");
			if (licensenPic.length > 10) {
				throw new BizException("图片最多上传10张！");
			}
			//新增驾校照图片
			ApplySchoolPic applySchoolPic = new ApplySchoolPic();
			applySchoolPic.setCreated(date);
			applySchoolPic.setUpdated(date);
			applySchoolPic.setIsDel(0);
			applySchoolPic.setDriversSchoolId(applySchool.getId());
			applySchoolPic.setType(1);
			for (int i = 0; i < licensenPic.length; i++) {
				if (licensenPic[i].trim() == null||licensenPic[i].trim() == "") {
					continue;
				}
				applySchoolPic.setFileId(Long.parseLong(licensenPic[i]));
				applySchoolPicMapper.insert(applySchoolPic);
			}
		}
	}

	@Override
	public void updateApplySchool(UpdateApplySchoolRo updateApplySchoolRo) throws BizException {
		//验证驾校
		Map<String, Object> map = new HashMap<>();
		map.put("valiPhone", updateApplySchoolRo.getMobile());
		map.put("valiId", updateApplySchoolRo.getId());
		List<ApplySchool> ApplySchoolRo = applySchoolMapper.queryListVo(map);
		if (ApplySchoolRo.size() > 0) {
			throw new BizException("请检查手机号码是否唯一！");
		}
		map.clear();
		map.put("valiId", updateApplySchoolRo.getId());
		map.put("valiCode", updateApplySchoolRo.getCode());
		ApplySchoolRo = applySchoolMapper.queryListVo(map);
		if (ApplySchoolRo.size() > 0) {
			throw new BizException("请检查驾校代码是否唯一！");
		}
		Date date = new Date();
		updateApplySchoolRo.setUpdated(date);
		updateApplySchoolRo.setStatus(1);
		ApplySchool applySchool = new ApplySchool();
		BeanUtils.copyProperties(updateApplySchoolRo, applySchool);
		this.baseMapper.updateById(applySchool);
		map.clear();
		map.put("driversSchoolId", updateApplySchoolRo.getId());
		if (updateApplySchoolRo.getDevicecode() != null || updateApplySchoolRo.getUsbKey() != null) {
			//修改设备
			List<ApplySchoolDevice> list = applySchoolDeviceMapper.queryList(map);
			if (list.size() > 1) {
				throw new BizException("驾校设备信息错误");
			} else if (list.size() == 1) {
				//有设备，修改设备
				ApplySchoolDevice asd = list.get(0);
				asd.setUsbKey(updateApplySchoolRo.getUsbKey());
				asd.setDevicecode(updateApplySchoolRo.getDevicecode());
				asd.setUpdated(date);
				applySchoolDeviceMapper.updateById(asd);
			} else if (list.size() == 2) {
				ApplySchoolDevice asd = new ApplySchoolDevice();
				asd.setUpdated(date);
				asd.setDevicecode(updateApplySchoolRo.getDevicecode());
				asd.setUsbKey(updateApplySchoolRo.getUsbKey());
				asd.setCreated(date);
				asd.setIsDel(0);
				asd.setDriversSchoolId(updateApplySchoolRo.getId());
				applySchoolDeviceMapper.insert(asd);
			}
		}
		List<ApplySchoolPic> list = applySchoolPicMapper.queryList(map);
		List<Long> schoolPics = new ArrayList<>();
		List<Long> licensenPics = new ArrayList<>();
		for (ApplySchoolPic applySchoolPic : list) {
			if (applySchoolPic.getType() == 1) {
				licensenPics.add(applySchoolPic.getFileId());
			} else {
				schoolPics.add(applySchoolPic.getFileId());
			}
		}
		//营业执照
		if (updateApplySchoolRo.getLicensenPics() != null) {
			String[] licensenPic = updateApplySchoolRo.getLicensenPics().split(",");
			updatePic(licensenPic, 1, updateApplySchoolRo.getId(), licensenPics);
		} else {
			//如果没有，则全部删除图片
			deletePic(licensenPics);
		}
		//驾校图片
		if (updateApplySchoolRo.getSchoolPics() != null) {
			String[] schoolPic = updateApplySchoolRo.getSchoolPics().split(",");
			updatePic(schoolPic, 2, updateApplySchoolRo.getId(), schoolPics);
		} else {
			deletePic(schoolPics);
		}
	}

	public void updatePic(String[] pic, Integer type, Long schoolId, List<Long> pics) throws BizException {
		Date date = new Date();
		List<Long> licensenPic = Arrays.asList(pic).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		if (licensenPic.size() > 10) {
			throw new BizException("图片最多上传10张！");
		}
		//新增营业执照图片
		ApplySchoolPic applySchoolPic = new ApplySchoolPic();
		applySchoolPic.setCreated(date);
		applySchoolPic.setUpdated(date);
		applySchoolPic.setIsDel(0);
		applySchoolPic.setDriversSchoolId(schoolId);
		applySchoolPic.setType(type);
		for (Long id : licensenPic) {
			if (!pics.contains(id)) {
				applySchoolPic.setFileId(id);
				applySchoolPicMapper.insert(applySchoolPic);
			}
		}
		//删除图片
		ApplySchoolPic del = new ApplySchoolPic();
		del.setUpdated(date);
		del.setIsDel(-1);
		for (Long id : pics) {
			if (!licensenPic.contains(id)) {
				del.setFileId(id);
				applySchoolPicMapper.updateByFileId(del);
			}
		}
	}

	public void deletePic(List<Long> pics) {
		ApplySchoolPic del = new ApplySchoolPic();
		del.setUpdated(new Date());
		del.setIsDel(-1);
		for (Long id : pics) {
			del.setFileId(id);
			applySchoolPicMapper.updateByFileId(del);
		}
	}

	@Override
	public void sendSmsMessage(String phone) {
		String code=getRandom();
		MessageRecordRo messageRecordRo=new MessageRecordRo();
		messageRecordRo.setPhone(phone);
		messageRecordRo.setSmsType(SmsType.sms_yzm);
		messageRecordRo.setMsgParams("[{paramKey:'code', paramValue:"+code+"}]");
		messageService.sendSmsMessage(messageRecordRo);
		//将验证码以<key,value>形式缓存到redis
		Map<String,Object> map=new HashMap<>();
		map.put("code",code);
		map.put("time",DateUtils.getNow());
		redisService.saveHash("code"+phone,map,System.currentTimeMillis());
	}

	@Override
	public void checkSmsMessage(String phone,String code) throws BizException, ParseException {
		Map<String,Object> checkCode =  redisService.getHash("code"+phone);
		if (checkCode == null){
			throw new BizException("验证码错误");
		}
		if (!checkCode.get("code").toString().equals(code)){
			throw new BizException("验证码错误");
		}
		Calendar beforeTime = Calendar.getInstance();
		beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
		Date fiveM = beforeTime.getTime();
		Date before=DateUtils.strToDate(checkCode.get("time").toString());
		Integer i=DateUtils.compareDate(fiveM,before);
		if(i!=-1){
			throw new BizException("验证码失效");
		}
	}

	@Override
	public void checkPicMessage(String captchaCode, String code) throws BizException {

	}

	// 获取6位随机验证码
	public static String getRandom() {
		String num = "";
		for (int i = 0 ; i < 6 ; i ++) {
			num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
		}
		return num;
	}

}











































